package com.ewzj.bigdata.mvp.ui.activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.ewzj.bigdata.R
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.extensions.loadImgwithloading
import com.ewzj.bigdata.di.component.DaggerMapActivityComponent
import com.ewzj.bigdata.di.module.MapActivityModule
import com.ewzj.bigdata.mvp.contract.MapActivityContract
import com.ewzj.bigdata.mvp.model.reqbean.ReqmapChangeBean
import com.ewzj.bigdata.mvp.model.rspbean.HomeBean
import com.ewzj.bigdata.mvp.presenter.MapActivityPresenter
import com.jakewharton.rxbinding2.view.RxView
import com.jess.arms.base.BaseActivity
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.UiUtils
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_map.*
import android.support.design.widget.BottomSheetBehavior
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.mvp.model.rspbean.BaseData
import com.ewzj.bigdata.mvp.model.rspbean.BaseListData
import com.ewzj.bigdata.mvp.ui.adapter.HomePageAdapter
import com.rey.material.app.BottomSheetDialog
import com.rey.material.widget.ProgressView


class MapActivity : BaseActivity<MapActivityPresenter>(), MapActivityContract.View, BaiduMap.OnMapLoadedCallback, BaiduMap.OnMarkerClickListener {
    val mBaiduMap by lazy { mapview.map }
    var type: Int =1
    var isCityMatch:Boolean=false
    var count=0
    var bottomSheetDialog : BottomSheetDialog? = null
    var homelistSheetDialog : BottomSheetDialog? = null
    val view by lazy { LayoutInflater.from(this).inflate(R.layout.bottomsheet_dialog_item, null) }
    val homelistview by lazy { LayoutInflater.from(this).inflate(R.layout.bottomsheet_dialog_list, null) }
    val emptyview by lazy { LayoutInflater.from(this).inflate(R.layout.error_view, null) }
    private var currentzoom: Float = 0.toFloat()
    var home:HomeBean?=null
    //    其他activity传过来的房源列表
    private var homeBeens: List<HomeBean>? = null
        get() {
            return intent.getParcelableArrayListExtra<HomeBean>(AppKey.EXTRA_DATA)
        }
    val hoursetype: String get() {
        when (type) {
            1 -> return "xinfang"
            2 -> return "ershoufang"
            3 -> return "zufang"
            else -> return ""
        }
    }

    override fun addAreMarker(homes: HomeBean) {
        addAreaMark(homes)
    }

    override fun clearMarker() {
        mBaiduMap.clear()
    }

    override fun addHomeMarker(home: HomeBean) {
        val markerOptions = getMarkerOption(home)
        val overlay = mBaiduMap.addOverlay(markerOptions)
        val bundle = Bundle()
        bundle.putParcelable(AppKey.EXTRA_MAP_DATA, home)
        overlay.extraInfo = bundle
    }

    override fun onMapLoaded() {
        currentzoom = mBaiduMap.mapStatus.zoom
    }

    override fun onMarkerClick(marker: Marker): Boolean {
        val bundle = marker.getExtraInfo()
        if (bundle != null) {
            val home = bundle.getParcelable<HomeBean>(AppKey.EXTRA_MAP_DATA)
            if (home.map_level.equals("house")) {
                when(hoursetype){
                    "ershoufang"->{
                        this.home=home
                        homelistview.findViewById(R.id.progress).visibility=View.VISIBLE
                        show(true,home.house_name)
                        mPresenter.getmapOldhome(home.region_id,home.house_name)
                    }
                    "zufang"->{
                        this.home=home
                        homelistview.findViewById(R.id.progress).visibility=View.VISIBLE
                        show(true,home.house_name)
                        mPresenter.getmapRenthome(home.region_id,home.house_name)
                    }
                    "xinfang"->showBSDialog(home)
                }
            } else if (home.map_level.equals("region")) {
                mBaiduMap.clear()
                currentzoom = 14.toFloat()
                changeMapCenter(home.lat, home.lon, 14)
                val req = ReqmapChangeBean(home.lon, home.lat, 1, 20, 14.toFloat(), hoursetype,mPresenter.currentCity.id)
                mPresenter.socketSendMsg(req)
            }
        }
        return false
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerMapActivityComponent.builder().appComponent(appComponent)
                .mapActivityModule(MapActivityModule(this))
                .build()
                .inject(this)
    }

    override fun initData(savedInstanceState: Bundle?) {
        type= intent.getIntExtra(AppKey.EXTRA_ID, 1)
        initBaiduMap()
        initListener()
        show(false,"")
        mPresenter.location(12)
        if(homeBeens==null){
            mPresenter.initRxsoket()
            mPresenter.socketConnect()
        }else{
            Observable.fromIterable(homeBeens).map { t ->t.apply { when(type){
                4->{ rg_type.visibility=View.GONE
                    tv_title.visibility=View.VISIBLE
                    tv_title.text="写字楼"}
                5->{
                    rg_type.visibility=View.GONE
                    tv_title.visibility=View.VISIBLE
                    tv_title.text="商铺"
                }
            } }  }.subscribe({ t -> addHomeMarker(t)  }, {
                t ->run{
                t.printStackTrace()
            }
            })

        }

    }


    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_map
    }

    override fun showLoading() {

    }

    override fun launchActivity(intent: Intent?) {

    }

    override fun hideLoading() {

    }

    override fun killMyself() {

    }

    override fun showMessage(message: String?) {

    }

    override fun init() {
        when (type) {
            1 -> rb_new.isChecked = true
            2 -> rb_old.isChecked = true
            3 -> rb_rent.isChecked = true
        }

    }

    private fun initListener() {
        RxView.clicks(iv_back).subscribe(Consumer { finish() })
        RxView.clicks(iv_locate).subscribe({mPresenter.location(currentzoom.toInt())})
        rg_type.setOnCheckedChangeListener { group, checkedId ->
            run {
                when (checkedId) {
                    R.id.rb_old -> run {
                        type=2
                        mPresenter.clearMapHome()
                        clearMarker()
                        if (isCityMatch&&count==0){
                            mPresenter.locationcitydata(2)
                        }else{
                            mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(12.toFloat()))
                            mPresenter.oldArea()
                        }

                    }
                    R.id.rb_new -> run {
                        type=1
                        mPresenter.clearMapHome()
                        clearMarker()
                        if (isCityMatch&&count==0){
                            mPresenter.locationcitydata(1)
                        }else{
                            mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(12.toFloat()))
                            mPresenter.newArea()
                        }

                    }
                    R.id.rb_rent -> run {
                        type=3
                        mPresenter.clearMapHome()
                        clearMarker()
                        if (isCityMatch&&count==0){
                            mPresenter.locationcitydata(3)
                        }else{
                            mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(12.toFloat()))
                            mPresenter.rentArea()
                        }

                    }
                }
                count++
            }
        }
    }

    private fun initBaiduMap() {
        mBaiduMap.mapType = BaiduMap.MAP_TYPE_NORMAL
        mBaiduMap.setOnMarkerClickListener(this)
        mBaiduMap.setMaxAndMinZoomLevel(12f, 18f)
        mBaiduMap.setOnMapLoadedCallback(this)
        mBaiduMap.setMyLocationEnabled(true)
        mapview.showZoomControls(false)

        var geo = BitmapDescriptorFactory.fromResource(R.drawable.icon_redlocation)
        val configuration = MyLocationConfiguration(
                MyLocationConfiguration.LocationMode.NORMAL, false, geo)
        configuration.accuracyCircleFillColor = resources.getColor(R.color.color_blue)
        mBaiduMap.setMyLocationConfigeration(configuration)// 设置定位模式

        mBaiduMap.setOnMapStatusChangeListener(object : BaiduMap.OnMapStatusChangeListener {
            override fun onMapStatusChangeStart(mapStatus: MapStatus) {

            }
            override fun onMapStatusChange(mapStatus: MapStatus) {
                if (mPresenter.maptype == 2 && mapStatus.zoom < 12 && homeBeens == null) {
                    if (mBaiduMap != null)
                        mBaiduMap.clear()
//                    mPresenter.location(12)
                    mPresenter.clearMapHome()
                    when (mPresenter.type) {
                        1 -> mPresenter.newArea()
                        2 -> mPresenter.oldArea()
                        3 -> mPresenter.rentArea()
                    }
                }
            }

            override fun onMapStatusChangeFinish(mapStatus: MapStatus) {
                val mcenterLatlng = mapStatus.target
                val lat = mcenterLatlng.latitude
                val lng = mcenterLatlng.longitude
                val zoom = mapStatus.zoom
                if (currentzoom == zoom && zoom >= 12 && homeBeens == null && mPresenter.maptype == 2) {
                    val req = ReqmapChangeBean(lng, lat, 1, 20, zoom, hoursetype,mPresenter.currentCity.id)
                    mPresenter.socketSendMsg(req)
                }
                currentzoom = zoom

            }
        })
    }

    //添加区域的marker
    fun addAreaMark(hourseBean: HomeBean?): Marker? {
        if (hourseBean == null) return null
        val bdStation = addMarker(hourseBean.region + "\n" + hourseBean.sum + "套")
        val showLatLng = LatLng(hourseBean.lat, hourseBean.lon)
        val ooA = MarkerOptions().position(showLatLng).icon(bdStation)
                .zIndex(9).period(100).draggable(false)
        //添加生长动画
        ooA.animateType(MarkerOptions.MarkerAnimateType.grow)
        val mMarkerA = mBaiduMap.addOverlay(ooA) as Marker
        val bundle = Bundle()
        bundle.putParcelable(AppKey.EXTRA_MAP_DATA, hourseBean)
        mMarkerA.extraInfo = bundle
        return mMarkerA
    }

    private fun addMarker(content: String): BitmapDescriptor {
        val view = View.inflate(this, R.layout.item_marker, null)
        val text = view.findViewById(R.id.home_name) as TextView
        text.text = content
        return BitmapDescriptorFactory.fromView(view)
    }

    override fun setMylocationData(lon: Double, lat: Double, zoom: Int) {
        val ll = LatLng(lat, lon)
        changeMapCenter(ll.longitude, ll.latitude, zoom)
        val data = MyLocationData.Builder()
                .accuracy(20.toFloat())
                .latitude(ll.longitude)
                .longitude(ll.latitude).build()
        mBaiduMap.setMyLocationData(data)
    }

    //    改变百度地图中心点位置
    override fun changeMapCenter(lon: Double, lat: Double, zoom: Int) {
        val cenpt = LatLng(lon, lat)
        //定义地图状态
        val mMapStatus = MapStatus.Builder()
                .zoom(zoom.toFloat())
                .target(cenpt)
                .build()
        currentzoom = zoom.toFloat()
        val mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus)
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate)
    }

    private fun getMarkerOption(hourseBean: HomeBean): MarkerOptions {
        var  bdStation: BitmapDescriptor?=null
        if (TextUtils.isEmpty(hourseBean.house_name)) {
            hourseBean.house_name="未知房源"
        }
        if (hourseBean.house_name.length > 10) {
            when(hoursetype){
                "xinfang"->bdStation = addMarker(hourseBean.name.substring(0, 8) +"..."+ "\n" + hourseBean.price)
                "ershoufang"->bdStation = addMarker(hourseBean.house_name.substring(0, 8) +"..."+ "\n" + "约"+hourseBean.sum+"套")
                "zufang"->bdStation = addMarker(hourseBean.house_name.substring(0, 8) +"..."+ "\n" + "约"+hourseBean.sum+"套")
            }

        } else {
            when(hoursetype){
                "xinfang"->bdStation = addMarker(hourseBean.name + "\n" + hourseBean.price)
                "ershoufang"->bdStation = addMarker(hourseBean.house_name+ "\n" +"约"+ hourseBean.sum+"套")
                "zufang"->bdStation = addMarker(hourseBean.house_name+ "\n" + "约"+hourseBean.sum+"套")
            }

        }

        val showLatLng = LatLng(hourseBean.lat, hourseBean.lon)
        val ooA = MarkerOptions().position(showLatLng).icon(bdStation)
                .zIndex(9).period(100).draggable(false)
        //添加生长动画
        ooA.animateType(MarkerOptions.MarkerAnimateType.grow)
        return ooA
    }

    override fun onDestroy() {
        mBaiduMap.clear()
        mapview.onDestroy()
        mPresenter.onDestroy()
        super.onDestroy()
    }

    override fun setZoomVisiable(isvisiable: Boolean) {
        if (isvisiable){
            isCityMatch=true
            iv_locate.visibility=View.VISIBLE
        }else{
            isCityMatch=false
            iv_locate.visibility=View.GONE
        }
    }

    //    点击弹框框
    private fun showBSDialog(homebean: HomeBean) {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = BottomSheetDialog(this)
            if (view.parent!=null){
                (view.parent as ViewGroup).removeView(view)
            }
            bottomSheetDialog!!.contentView(view)
                    .heightParam(ViewGroup.LayoutParams.WRAP_CONTENT)
                    .inDuration(500)
                    .cancelable(true)
                    .canceledOnTouchOutside(true)
        }

        (view.findViewById(R.id.iv_pic) as ImageView).loadImgwithloading(Apputils.Utils.getImgUrl(homebean.thumb))
        (view.findViewById(R.id.tv_title) as TextView).text = homebean.name
        (view.findViewById(R.id.tv_price)as TextView).text = "均价" + homebean.price
        (view.findViewById(R.id.tv_size)as TextView).text = "建筑面积" + homebean.area
        view.setOnClickListener(View.OnClickListener {
            bottomSheetDialog!!.dismiss()
            HomeWebActivity.startHomeActivity(this, homebean)
        })
        bottomSheetDialog!!.setOnDismissListener { bottomSheetDialog=null }
        bottomSheetDialog!!.show()
    }
    override fun showpopListview(data: BaseData<BaseListData<HomeBean>>,title:String) {
        homelistview.findViewById(R.id.progress).visibility=View.GONE
        var rv=homelistview.findViewById(R.id.rvlist) as RecyclerView
        (rv.adapter as HomePageAdapter).setNewData(data.data!!.list)
        try {
            var home=data.data!!.list
            if (home.size==0){
                if (homelistSheetDialog!=null&&homelistSheetDialog!!.isShowing){
                    homelistSheetDialog!!.dismiss()
                }
                UiUtils.makeText(this,"未找到相关房源信息")
            }
            (homelistview.findViewById(R.id.areades) as TextView).setText("觅窝为您找到房源 ："+home.size+"套")
        }catch (e:Exception){
            e.printStackTrace()
        }


    }

    override fun show(boolean: Boolean,title:String) {
        if (homelistSheetDialog == null) {
            homelistSheetDialog = BottomSheetDialog(this)
            if (homelistview.parent!=null){
                (homelistview.parent as ViewGroup).removeView(homelistview)
            }
            homelistSheetDialog!!.contentView(homelistview)
                    .heightParam(ViewGroup.LayoutParams.WRAP_CONTENT)
                    .inDuration(500)
                    .cancelable(true)
                    .canceledOnTouchOutside(true)
        }
        var rv=homelistview.findViewById(R.id.rvlist) as RecyclerView
        (homelistview.findViewById(R.id.tv_title) as TextView).setText(title)
        if (rv.adapter==null){
            var homeadapter=HomePageAdapter(ArrayList<HomeBean>())
            rv.layoutManager=LinearLayoutManager(this)
            rv.adapter=homeadapter
        }else{
//            var layoutprams=emptyview.findViewById(R.id.iv_error).layoutParams as RelativeLayout.LayoutParams
//            layoutprams.topMargin=20
//            emptyview.findViewById(R.id.iv_error).layoutParams=layoutprams
//            (rv.adapter as HomePageAdapter).emptyView=emptyview
        }
        homelistSheetDialog!!.setOnDismissListener {
            homelistSheetDialog=null
        }
        homelistSheetDialog!!.setOnDismissListener {
            homelistSheetDialog=null
        }
        RxView.clicks(homelistview.findViewById(R.id.tv_close)).subscribe { homelistSheetDialog!!.dismiss() }
        if (homelistSheetDialog!=null&&boolean){
            homelistSheetDialog!!.show()
        }
    }

    override fun onPause() {
        super.onPause()
//        if (homelistSheetDialog!=null){
//            homelistSheetDialog!!.dismiss()
//        }
    }
}
